package org.base.common.util;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.function.Consumer;

/**
 * 对象拷贝工具类
 *
 */
@Slf4j
public class ObjectCopyUtils {


    public static <T, S> T copy(S src, Class<T> clazz) {
        try {
            final T instance = clazz.newInstance();
            BeanUtils.copyProperties(src, instance);
            return instance;
        } catch (Exception e) {
            log.warn(e.getMessage(), e);
        }
        return null;
    }

    public static <T, S> T copy(S src, Class<T> clazz, Consumer<T> consumer) {
        final T instance = copy(src, clazz);
        if (instance != null) {
            consumer.accept(instance);
        }
        return instance;
    }

    public static <T, S> List<T> copy(Collection<S> coll, Class<T> clazz, Consumer<T> consumer) {
        try {
            List<T> result = new ArrayList<>();
            for (S item : coll) {
                result.add(copy(item, clazz, consumer));
            }
            return result;
        } catch (Exception e) {
            log.warn(e.getMessage(), e);
        }
        return null;
    }

    public static <T, S> List<T> copy(Collection<S> coll, Class<T> clazz) {
        return copy(coll, clazz, e ->{});
    }
}
